package com.geeklan.smart.ui;

import android.os.Handler;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.data.repository.user.AccountRepository;
import com.geeklan.smart.databinding.ActivitySplashBinding;
import com.geeklan.smart.ui.login.LoginActivity;
import com.geeklan.smart.ui.main.MainActivity;
import com.geeklan.smart.ui.viewmodel.user.UserViewModel;
import com.geeklan.smart.ui.viewmodel.user.UserViewModelFactory;
import com.geeklan.smart.utils.SharedPreferencesUtil;

public class SplashActivity extends BaseActivity<ActivitySplashBinding> {
    private UserViewModel userViewModel;

    @Override
    protected ActivitySplashBinding initBinding() {
        return ActivitySplashBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        userViewModel = new ViewModelProvider(this, new UserViewModelFactory(new AccountRepository())).get(UserViewModel.class);

        userViewModel.getTokenLoginPwdLiveData().observe(this, response -> {
            dismiss();
            SharedPreferencesUtil.putString("token", response.getToken());
        });

        userViewModel.getErrorLiveData().observe(this, s -> {
            dismiss();
//            Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
        });

        String token = SharedPreferencesUtil.getString("token", "");
        if (!token.isEmpty()) {
            userViewModel.tokenLogin(token);
        }

        new Handler().postDelayed(() -> {
            boolean isLogin = SharedPreferencesUtil.getBoolean("isLogin", false);
            if (isLogin) {
                MainActivity.startActivity(this);
            } else {
                LoginActivity.startLogin(this);
            }
            finish();
        }, 3000);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }
}